package com.lucky.common.schedule;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ScheduledFuture;

public class TaskUtil {

    static final Logger logger = LoggerFactory.getLogger(TaskUtil.class);

    static ThreadPoolTaskScheduler scheduledPool = new ThreadPoolTaskScheduler();

    static Map<String, ScheduledFuture<?>> scheduledMap = new HashMap<>();


    static{
        scheduledPool.setPoolSize(5);
        // 这里给线程设置名字，主要是为了在项目能够更快速的定位错误。
        scheduledPool.setThreadGroupName("TaskUtil");
        scheduledPool.setThreadNamePrefix("TaskUtilThread-");
        scheduledPool.initialize();
        scheduledPool.initialize();
    }


    public static void add(Runnable runnable, Trigger trigger, String id) {
        ScheduledFuture<?> sf = scheduledPool.schedule(runnable, trigger);
        scheduledMap.put(id, sf);
        logger.info("----------add scheduler finish-----------{}", id);
    }


    public static void remove(String id) {
        ScheduledFuture<?> sf = scheduledMap.get(id);
        if(sf != null && sf.isCancelled()) {
            sf.cancel(true);
        }

        scheduledMap.remove(id);
        logger.info("----------delete scheduler finish-----------{}", id);
    }
}
